package com.changgou.service.impl;


import com.alibaba.fastjson.JSON;
import com.changgou.dao.ESManagerMapper;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.service.ESManagerService;
import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ESManagerServiceImpl implements ESManagerService {

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private ESManagerMapper esManagerMapper;

    //创建索引库结构
    @Override
    public void createMappingAndIndex() {
        //创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //创建映射
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    //导入全部sku集合进入索引库
    @Override
    public void importAll() {
        //查询全部sku集合
        List<Sku> skuList = skuFeign.findSkuListBySpuId("all");
        if (skuList == null  || skuList.size() <= 0 ){
            throw new RuntimeException("当前没有数据被查询到，无法导入索引库");
        }
        //将skuList转换为json
        String jsonSkuList = JSON.toJSONString(skuList);
        //将json转换为SkuInfo
        List<SkuInfo> skuInfoList = JSON.parseArray(jsonSkuList, SkuInfo.class);

        //将规格数据转化为map
        for (SkuInfo skuInfo : skuInfoList) {
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        //导入索引库
        esManagerMapper.saveAll(skuInfoList);
    }

    //根据spuid查询skuList，添加到索引库
    @Override
    public void importDataToESBySpuId(String spuid) {
        //查询全部sku集合
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuid);
        if (skuList == null  || skuList.size() <= 0 ){
            throw new RuntimeException("当前没有数据被查询到，无法导入索引库");
        }
        //将skuList转换为json
        String jsonSkuList = JSON.toJSONString(skuList);
        //将json转换为SkuInfo
        List<SkuInfo> skuInfoList = JSON.parseArray(jsonSkuList, SkuInfo.class);

        //将规格数据转化为map
        for (SkuInfo skuInfo : skuInfoList) {
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        //导入索引库
        esManagerMapper.saveAll(skuInfoList);
    }

    //从索引库中根据spuId删除数据
    @Override
    public void deleteDataToESBySpuId(String spuId) {
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
        if (skuList == null || skuList.size() <= 0){
            throw new RuntimeException("当前没有查询到相应数据，无法删除");
        }
        for (Sku sku : skuList) {
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }
    }
}
